package com.express.sys.controller;

import com.alibaba.fastjson.JSONObject;
import com.express.conf.WechatConfig;
import com.express.constants.Constants;
import com.express.emnus.OrderStatusEnum;
import com.express.entity.UserOrders;
import com.express.entity.wx.AccessToken;
import com.express.entity.wx.TemplateData;
import com.express.entity.wx.WxTemplate;
import com.express.mybatis.PageResult;
import com.express.mybatis.Result;
import com.express.service.IAddressService;
import com.express.service.IOrderService;
import com.express.service.IWxUserService;
import com.express.util.DateUtils;
import com.express.util.ExcelUtil;
import com.express.util.wx.WeixinUtil;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.function.Function;

@RestController
@RequestMapping({"/sysOrder"})
public class SysOrderController {

    private static Logger logger = LoggerFactory.getLogger(SysOrderController.class);

    @Autowired
    IOrderService iOrderService;
    @Autowired
    IWxUserService wxUserService;
    @Autowired
    IAddressService addressService;

    @PostMapping({"/list"})
    public PageResult list(PageResult page) {
        PageResult result = null;
        int pageNumber = page.getPageNum();
        int pageSize = page.getPageSize();
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("status", "1");
            PageHelper.startPage(pageNumber, pageSize);
            List<UserOrders> list = iOrderService.getList(map);
            list.forEach(l -> {
                        if (StringUtils.isNotBlank(l.getBackPicPath())) {
                            l.setPics(l.getBackPicPath().split(","));
                        }
                        l.setOrderNo(l.getOrderNo().replace(Constants.ENV_PREFIX, ""));
                    }
            );
            result = new PageResult(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @PostMapping("/add")
    public PageResult add(@RequestBody UserOrders userOrders) {
        PageResult result = new PageResult();
        try {
            this.iOrderService.save(userOrders);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @PostMapping({"/update"})
    public Result update(@RequestBody UserOrders userOrders) {
        Result result = new Result();
        this.iOrderService.update(userOrders);
        return result;
    }

    /**
     * 订单导出
     *
     * @param userOrders
     * @param response
     * @return
     */
    @RequestMapping("/export")
    public void export(UserOrders userOrders, String[] ids, HttpServletResponse response) {
        try {
            List<UserOrders> list = new ArrayList<>();
            Function<int[], List> get = i -> {
                return iOrderService.getOrderByIds(i);
            };
            list = Optional.ofNullable(ids).map(i -> {
                int[] idsInt = new int[i.length];
                for (int j = 0; j < i.length; j++) {
                    idsInt[j] = Integer.parseInt(i[j]);
                }
                return get.apply(idsInt);
            }).orElse(null);
            if (null == list || list.size() == 0) {
                Map<String, Object> map = new HashMap<>();
                map.put("userId", userOrders.getId());
                list = iOrderService.getList(map);
            }
            List<String> titles = Arrays.asList("序号", "订单号", "发件人姓名", "手机号", "公司", "接收地址", "物品类型", "件数", "重量",
                    "是否有台车", "创建时间", "备注");
            List<Object[]> datas = new ArrayList<>();
            int i = 1;
            for (UserOrders obj : list) {
                Object[] data = {i, obj.getOrderNo(), obj.getSendName(), obj.getSendPhone(), obj.getSendCompany(), obj.getReceiveAddress(),
                        obj.getGoodsType(), obj.getGoodsNumber(), obj.getWeight(), obj.getUseCar(), DateUtils.matter1.format(obj.getCreateDate()), obj.getRemark()};
                datas.add(data);
                i++;
            }
            String fileName = "订单列表";
            ExcelUtil.exportBigDataExcell(ExcelUtil.getWorkBook(), titles, datas, response,
                    fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询订单
     *
     * @param pageNum
     * @param pageSize
     * @param mobile
     * @param date
     * @return
     */
    @GetMapping({"/search"})
    public PageResult search(int pageNum, int pageSize, String mobile, String date,String oddNumber,
                             String orderStatus) {
        PageResult result = new PageResult();
        try {
            String[] dates = StringUtils.isNotBlank(date) ? date.split(",") : null;
            String startDate = "", endDate = "";
            if (dates != null && dates.length >= 1) {
                startDate = dates[0];
                endDate = dates[1];
            }
            Map<String, Object> map = new HashMap<>();
            map.put("phone", mobile);
            map.put("startDate", startDate);
            map.put("endDate", endDate);
            map.put("oddNumber", oddNumber);
            if(StringUtils.isNotBlank(orderStatus)){
                map.put("orderStatus", OrderStatusEnum.getOrderStatus(orderStatus));
            }
            PageHelper.startPage(pageNum, pageSize);
            List<UserOrders> list = iOrderService.getList(map);
            result = new PageResult(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 通知来新订单
     *
     * @return
     */
    @PostMapping({"/notifyMsg"})
    public Result notifyMsg() {
        Result result = null;
        String msg = this.iOrderService.getNewOrder();
        result = new Result("通知用户下单了", 200, true);
        result.setData(msg);
        result.setStatus("200");
        return result;
    }

    /**
     * 已读订单
     *
     * @param userOrders
     * @return
     */
    @PostMapping({"/read"})
    public Result read(@RequestBody UserOrders userOrders) {
        Result result = null;
        try {
            Map<String, Object> param = new HashMap<>();
            param.put("id", userOrders.getUserId());
            String openid = Optional.ofNullable(wxUserService.query(param))
                    .map(u -> u.get(0).getOpenId()).orElse("");
            logger.info("发送给用户的openid:" + openid);
            // 发送微信模版消息
            AccessToken accessToken = WeixinUtil.getAccessToken(WechatConfig.APP_ID, WechatConfig.APP_SECRET);
            WxTemplate template = WeixinUtil.getTemplate(WechatConfig.WEIXIN_YD_MSGID, openid);
            Map<String, TemplateData> map = new HashMap();
            map.put("first", new TemplateData("你有新的快件信息。", "#0000FF"));
            map.put("character_string10", new TemplateData(userOrders.getOrderNo(), "#000000"));
            map.put("character_string1", new TemplateData(userOrders.getOddNumber(), "#000000"));
            param.clear();

            param.put("id", userOrders.getReceiveId());
            String name = Optional.ofNullable(addressService.query(param))
                    .map(u -> u.get(0).getName()).orElse("");
            map.put("thing5", new TemplateData(name, "#000000"));
            map.put("time2", new TemplateData(DateUtils.matter1.format(new Date()), "#000000"));
            map.put("remark", new TemplateData("您的寄件信息已经收到，感谢您对莱比特物流的支持，欢迎下次使用。", "#0000FF"));
            template.setData(map);
            int re = WeixinUtil.sendMessage(template, accessToken.getToken());
            if (re == 0) {
                result = new Result("已经查阅订单成功，并发微信消息通知用户", 200, true);
                result.setStatus("200");
                // 设置为已读
                userOrders.setIsRead(1);
                this.iOrderService.update(userOrders);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = new Result("出现异常，请检查。", 201, false);
        }
        return result;
    }

    // 取消订单
    @PostMapping({"/cancelOrder"})
    public Result cancelOrder(@RequestBody JSONObject json) {
        Result result = new Result();
        String[] idsArr = json.getString("ids").split(",");
        int[] idsInt = new int[idsArr.length];
        for (int i = 0; i < idsArr.length; i++) {
            idsInt[i] = Integer.parseInt(idsArr[i]);
        }
        List<UserOrders> orderByIds = this.iOrderService.getOrderByIds(idsInt);
        if (orderByIds != null && orderByIds.size() > 0) {
            orderByIds.forEach(o -> {
                o.setStatus(9);
                o.setUpdateDate(new Date());
                o.setRemark((o.getRemark() == null ? "" : o.getRemark()) + ",由管理员取消订单");
                iOrderService.update(o);
            });
            result = new Result("已经取消订单成功", 200, true);
            result.setStatus("200");
        }
        return result;
    }

}